package viewbuilder

class HtmlBuilder extends BuilderSupport {

    public static final Integer CLOSED_ELEMENT = 1
    public static final Integer OPENED_ELEMENT = 2
    public static final Integer TEXT_ELEMENT = 3


    int state
    Writer writer

    HtmlBuilder(Writer writer) {
        this.writer = writer
    }

    protected void setParent(Object parent, Object child) {
    }

    protected Object createNode(Object name) {
        return createNode(name, null, null)
    }

    protected Object createNode(Object name, Object value) {
        return createNode(name, null, value)
    }

    protected Object createNode(Object name, Map attributes) {
        return createNode(name, attributes, null)
    }

    protected Object createNode(Object name, Map attributes, Object value) {

        if (state == OPENED_ELEMENT) {
            writer << ">\n"
        }
        if (name == "text" && value) {
            writer << "${value}"
            state = TEXT_ELEMENT
        } else {
            writer << "<${name}"
            if (attributes) {
                attributes.each {key, val ->
                    writer << " ${key}='${val}'"
                }
            }
            state = OPENED_ELEMENT

            if (value) {
                writer << ">${value}"
                state = CLOSED_ELEMENT
            }
        }

        return name
    }

    protected void nodeCompleted(Object parent, Object node) {
        switch(state) {
            case CLOSED_ELEMENT:
                writer << "</${node}>"
                break
            case OPENED_ELEMENT:
                writer << "/>"
                break

        }
        state = CLOSED_ELEMENT
        writer << "\n"
    }
}